package edu.gdut.tiantian.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import edu.gdut.tiantian.entity.Product;

@Repository
public interface ProductDao {
	
	@SelectKey(before = true,keyColumn = "productId",keyProperty = "productId",statement = "select replace(uuid(),'-','')", resultType = String.class)
	@Insert("insert into product(productId,productName,productDesc,categoryId,price,isNew,isCommend,discount,stock,productNum) values("
			+ "#{productId},#{productName},#{productDesc},#{categoryId},#{price},#{isNew},#{isCommend},#{discount},#{stock},#{productNum})")
	void save(Product product);
	
	//删除商品
	@Delete("delete from product where productId=#{productId}")
	void delete(String productId);
	
	//更新商品
	@Update("update product set"
			+ " productName=#{productName},productDesc=#{productDesc},categoryId=#{categoryId},price=#{price},"
			+ "isNew=#{isNew},isCommend=#{isCommend},discount=#{discount},stock=#{stock},productNum=#{productNum}")
	void update(Product product);
	
	@Select("select * from product where productId=#{productId}")
	Product findById(String productId);
	
	//条件查询
		@Select("<script> select * from product where 1=1 "
				+ "<foreach collection='condition' index='keys' item='values'>"
				+ "<if test='keys == " +"\"categoryId\" and keys != null and values!=0" +"'>and categoryId=#{values}</if>"
				+ "<if test='keys == " +"\"productNum\" and keys != null" +"'>and productNum like CONCAT('%',#{values},'%')</if>"
				+ "<if test='keys == " +"\"productName\" and keys != null" +"'>and productName like CONCAT('%',#{values},'%')</if>"
				+ "<if test='keys == " +"\"lowPrice\" and keys != null" +"'>and price &gt;=#{values}</if>"
				+ "<if test='keys == " +"\"highPrice\" and keys != null" +"'>and price &lt;=#{values}</if>"
				+ "</foreach>"
				+ "</script>")
		@Results({
			@Result(property = "category",column = "categoryId",one = @One(select="edu.gdut.tiantian.dao.CategoryDao.findById"))
		})
	List<Product> findByCondition(@Param("condition")Map<String,String> condition);
		
	@Select("select * from product where isCommend=1")
	List<Product> getCommend();
	
	@Select("select * from product where isNew=1")
	List<Product> getNew();
}
